import requests
from database.sqlite import tsdb,historydb
# from push import logger
import time
import arrow
import requests
from draw import draw
# from upload.qn import upload_image
import chardet
from notify.ding import Ding

check_dic = {}
TS_DB = tsdb.TSDB('./data/time_series.db')
HIS_DB = historydb.historyDB('./data/history.db')
ding = Ding()



def upload_image(path):

    try:
        with open(path,'rb')as f:
            # response = requests.request("POST", "https://x.mouto.org/wb/x.php?up", data=f)
            # print(response.text)
            # pid = response.json()['pid']
            data = {'file':f,'name':"file", 'filename':"005.jpg", 'Content-Type':'image/jpeg'}
            response = requests.request("POST", 'http://61.171.85.237:672/v1/upload', files=data)
            print(response.text)
            pid = response.json()['wbpid']
            # return 'https://ww4.sinaimg.cn/large/%s'%pid
            return 'http://ww2.sinaimg.cn/large/%s.jpg'%pid
    except Exception as e:
        print(e)
        return ""

def honglin_sum():
    header= {'Accept':'application/json, text/javascript, */*; q=0.01'}
    req = requests.get('http://www.p2peye.com/shuju/ptsj/',headers=header)
    # ret = chardet.detect(req.content)
    bt = req.text
    print(bt)

def honglin():
    data = {'currentPage':1,'oc_':3,'ou_':1,}
    header= {'Accept':'application/json, text/javascript, */*; q=0.01'}
    ret = requests.post("https://investment.my089.com/credit/index",data=data,headers=header)
    jd = ret.json()['list'][0]

    his = []
    for i in range(1,4):
        ret = requests.post("https://investment.my089.com/credit/index",data={'currentPage':i},headers=header)
        his.extend(ret.json()['list'])
    for each in his:
        check_dic.setdefault(each.get('subjectID'),each.get('publishTime'))
        if each.get('publishTime') != check_dic[each.get('subjectID')]:
            print('double key')
            print(each)
        else:
            HIS_DB.save('hlct',each.get('subjectID'),each.get('publishTime'),each.get('uiloginUserNamed'),each)
    TS_DB.save('hlct',jd.get('amount'),jd.get('interestRate'),jd)
    # return {
    #     'loginUserName':jd.get("loginUserName"),
    #     'memberLevel':jd.get("memberLevel"),
    #     'termOfMonth':jd.get("termOfMonth"),
    #     'interestRate':jd.get("interestRate"),
    #     'remainderAmount':jd.get("remainderAmount"),
    #     'amount':jd.get("amount"),
    #     'time': arrow.now().format("HH:mm:ss")
    # }
    jd['time'] = arrow.now().format("HH:mm:ss")
    return jd

def hl_loop(radio=0.05, delay=3600):
    msg = """红岭新标 {time}
    利率：{interestRate} %/年
    期限：{termOfMonth} 月
    金额：{amount} 元
    余量：{remainderAmount} 元
    借款者：{loginUserName} (V{memberLevel}）"""

    data_temp = None
    hour_temp = 0
    def draw_png():
        ts_data = []
        for each in TS_DB.select('hlct',limit=600):
            ts_data.append({'time':arrow.get(each.get('updatetime')).to('local').format('YYYY-MM-DD HH:mm:ss'),'rate':each.get('interestRate')})
        png_path = draw(ts_data)
        png_url = upload_image(png_path,)
        return png_url


    while 1:
        try:
            dic = honglin()
            if arrow.now().hour >22 or arrow.now().hour < 8:
                time.sleep(20)
                continue
            if hour_temp != arrow.now().hour:
                hour_temp = arrow.now().hour
                png_path = draw_png()
                ding.send_md('最近走势',"> ![screenshot](%s)"%png_path)
                # logger.send_image(png_path)
        except Exception as e:
            print(e)
            time.sleep(20)
            continue
        if not data_temp:
            time_temp = arrow.now()
            data_temp = dic
            my_msg = msg.format_map(dic)
            ding.send_message(my_msg)
            # png_path = draw_png()

            # ding.send_md('最近走势',"> ![screenshot](%s)"%png_path)
        else:
            tp = arrow.now() - time_temp
            if abs(dic.get('interestRate') - data_temp.get('interestRate'))>=radio or tp.seconds>delay:
                time_temp = arrow.now()
                data_temp = dic
                my_msg = msg.format_map(dic)
                png_path = draw_png()
                ding.send_message(my_msg)
                ding.send_md('最近走势',"> ![screenshot](%s)"%png_path)


        time.sleep(20)

if __name__ == '__main__':
    hl_loop(radio=0.05,delay=3600)
    # honglin_sum()
